package com.plat.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.internal.CriteriaImpl;

import com.plat.core.hibernate.HibernateGenericDao;
import com.plat.core.hibernate.qbc.CriteriaQuery;
import com.plat.core.hibernate.qbc.PagerUtil;
import com.plat.dao.IBaseDao;
import com.plat.tag.core.easyui.ComboTreeModel;
import com.plat.tag.core.easyui.TreeGridModel;
import com.plat.tag.core.json.ComboTree;
import com.plat.tag.core.json.DataGridReturn;
import com.plat.tag.core.json.TreeGrid;
import com.plat.tag.core.utils.ReflectHelper;
import com.plat.tag.core.utils.TagUtil;

public abstract class BaseDaoImpl<T> extends HibernateGenericDao<T> implements IBaseDao<T> {

    @Override
    public DataGridReturn getDataGridReturn(CriteriaQuery cq, boolean b) {
        Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(getSession());
        CriteriaImpl impl = (CriteriaImpl) criteria;
        // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
        Projection projection = impl.getProjection();
        final int allCounts = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
        criteria.setProjection(projection);
        if (projection == null) {
            criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
        }
        if (StringUtils.isNotBlank(cq.getDataGrid().getSort())) {
            cq.addOrder(cq.getDataGrid().getSort(), cq.getDataGrid().getOrder());
        }

        // 判断是否有排序字段
        if (!cq.getOrdermap().isEmpty()) {
            cq.setOrder(cq.getOrdermap());
        }
        int pageSize = cq.getPageSize();// 每页显示数
        int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(), pageSize);// 当前页
        int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
        if (b) {// 是否分页
            criteria.setFirstResult(offset);
            criteria.setMaxResults(cq.getPageSize());
        } else {
            pageSize = allCounts;
        }
        // DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(),
        // cq.getField().split(","), cq.getClass1(), false);
        List list = criteria.list();
        cq.getDataGrid().setReaults(list);
        cq.getDataGrid().setTotal(allCounts);
        return new DataGridReturn(allCounts, list);
    }

    public List<ComboTree> comboTree(List all, ComboTreeModel comboTreeModel, List in) {
        List<ComboTree> trees = new ArrayList<ComboTree>();

        for (Object o : all) {
            trees.add(comboTree(o, comboTreeModel, in, false));
        }
        return trees;
    }

    private ComboTree comboTree(Object o, ComboTreeModel comboTreeModel, List in, boolean recursive) {
        ComboTree tree = new ComboTree();
        Map<String, Object> attributes = new HashMap<String, Object>();
        ReflectHelper reflectHelper = new ReflectHelper(o);
        String id = String.valueOf(reflectHelper.getMethodValue(comboTreeModel.getIdField()));
        tree.setId(id);
        tree.setText(String.valueOf(reflectHelper.getMethodValue(comboTreeModel.getTextField())));
        if (comboTreeModel.getSrcField() != null) {
            attributes.put("href", String.valueOf(reflectHelper.getMethodValue(comboTreeModel.getSrcField())));
            tree.setAttributes(attributes);
        }

        //设置选中的菜单
        if (in != null && in.size() > 0) {
            for (Object inobj : in) {
                ReflectHelper reflectHelper2 = new ReflectHelper(inobj);
                String inId = String.valueOf(reflectHelper2.getMethodValue(comboTreeModel.getIdField()));
                if (inId == id) {
                    tree.setChecked(true);
                }
            }
        }

        List<?> childFields = (List<?>) reflectHelper.getMethodValue(comboTreeModel.getChildField());

        if (childFields != null && childFields.size() > 0) {
            tree.setState("closed");
            tree.setChecked(false);
        }
        return tree;
    }
    
    @Override
    public List<TreeGrid> treegrid(List all, TreeGridModel treeGridModel) {
        List<TreeGrid> treegrid = new ArrayList<TreeGrid>();
        for (Object obj : all) {
            ReflectHelper reflectHelper = new ReflectHelper(obj);
            TreeGrid tg = new TreeGrid();
            String id = String.valueOf(reflectHelper.getMethodValue(treeGridModel.getIdField()));
            String src = String.valueOf(reflectHelper.getMethodValue(treeGridModel.getSrc()));
            String text = String.valueOf(reflectHelper.getMethodValue(treeGridModel.getTextField()));
            
            if(StringUtils.isNotEmpty(treeGridModel.getOrder())){
                String order = String.valueOf(reflectHelper.getMethodValue(treeGridModel.getOrder()));
                tg.setOrder(order);
            }
            tg.setId(id);
            if (treeGridModel.getIcon() != null) {
                String iconpath = TagUtil.fieldNametoValues(treeGridModel.getIcon(), obj).toString();
                if (iconpath != null) {
                    tg.setCode(iconpath);
                } else {
                    tg.setCode("");
                }
            }
            tg.setSrc(src);
            tg.setText(text);
            if (treeGridModel.getParentId() != null) {
                Object pid = TagUtil.fieldNametoValues(treeGridModel.getParentId(), obj);
                if (pid != null) {
                    tg.setParentId(pid.toString());
                } else {
                    tg.setParentId("");
                }
            }
            if (treeGridModel.getParentText() != null) {
                Object ptext = TagUtil.fieldNametoValues(treeGridModel.getTextField(), obj);
                if (ptext != null) {
                    tg.setParentText(ptext.toString());
                } else {
                    tg.setParentText("");
                }

            }
            List childList = (List) reflectHelper.getMethodValue(treeGridModel.getChildList());

            if (childList != null && childList.size() > 0) {
                tg.setState("closed");
            }
            
            treegrid.add(tg);
        }
        return treegrid;
    }
}
